/*
 * TopicPortal.java
 *
 * Created on November 25, 2007, 1:56 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package source.jms;

import java.util.ArrayList;
import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import javax.jms.Message;
import javax.naming.NamingException;
import server.utils.ServiceLocator;

/**
 *
 * @author alexogar
 */
public class TopicPortal {
    
    private TopicConnection connection;
    
    private TopicSession session;
    
    private Topic topic;
    
    private TopicPublisher publisher;
    
    private TopicSubscriber subscriber;
    
    private String name;        
    
    private String messageSelector;
    
    /** Creates a new instance of TopicPortal */
    public TopicPortal(String name) {
        this.name = name;
    }
    
    public void configure(String jndiConnFactoryName,String topicName) {
        try {
            connection = ServiceLocator.getInstance().getTopicConnectionFactory(jndiConnFactoryName).createTopicConnection();
            connection.start();
            session = connection.createTopicSession(false,Session.AUTO_ACKNOWLEDGE);
            topic = session.createTopic(topicName);
            publisher = session.createPublisher(topic);
            if ((messageSelector==null)||(messageSelector=="")) {
                subscriber = session.createDurableSubscriber(topic,name);
            } else {
                subscriber = session.createDurableSubscriber(topic,name,messageSelector,true);
            }
        } catch (JMSException ex) {
            ex.printStackTrace();
        } catch (NamingException ex) {
            ex.printStackTrace();
        }
    }
    
    public void publish(Message msg) throws JMSException {
        publisher.publish(msg);
    }
    
    public ArrayList<Message> receive() {
        
    }
    
    public void close() {
        try {
            connection.close();
            // cleanup
            publisher.close();
            session.close();
        } catch (JMSException ex) {
            ex.printStackTrace();
        }
    }
    
}
